﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Thrift;
using System.IO;

namespace SearchInterface.helper
{
    static class Utilities
    {
        public static String GetUserConfigurationPath()
        {
            string homePath = (Environment.OSVersion.Platform == PlatformID.Unix ||
                   Environment.OSVersion.Platform == PlatformID.MacOSX)
                ? Environment.GetEnvironmentVariable("HOME")
                : Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
            return Path.Combine(homePath, "hydrap2p");
        }
        public static String GetSharedConfigurationPath()
        {
            String ProgramFiles = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);
            String ThePath = Path.Combine(ProgramFiles, "HydraP2P");
            if (!System.IO.Directory.Exists(ThePath))
            {
                ThePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "conf");
            }
            return ThePath;
        }

        /// <summary>
        /// Determines what port the Manager is supposed to be running at, by searching through the configuration
        /// </summary>
        /// <exception cref="FileNotFoundException">No valid configuration could be found</exception>
        /// <exception cref="FormatException">The port number found in the configuration is not a valid number</exception>
        /// <returns></returns>
        public static int GetManagerPort()
        {
            String ConfPath = GetUserConfigurationPath();
            String FilePath = Path.Combine(ConfPath, "servicemanager.ini");
            if (!File.Exists(FilePath))
            {
                ConfPath = GetSharedConfigurationPath();
                FilePath = Path.Combine(ConfPath, "servicemanager.ini");
            }
            if (!File.Exists(FilePath))
                throw new FileNotFoundException("Could not find Manager's configuration", FilePath);

            IniFile file = new IniFile(FilePath);
            file.Load();
            int port=0;

            // may throw FormatException
            IniSection sect=file["main"];
            if (file.HasSection("main"))
                if (file["main"].HasKey("port"))
                    port = int.Parse(file["main"]["port"].Trim());
            return port;
        }

    }
}
